import React, { useEffect, useState } from 'react'
import { Table, Tag, Button, Modal, Popover, Switch } from 'antd'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import {getRights,updateRights,deleteRights,updateChildren,deleteChildren} from "../../../api/api"

export default function RightList() {
  const [dataSource, setDataSource] = useState([]);
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => {
        return <b>{id}</b>
      }
    },
    {
      title: '权限名称',
      dataIndex: 'title',
    },
    {
      title: '权限路径',
      dataIndex: 'key',
      render: (key) => {
        return <Tag color="orange">{key}</Tag>
      }
    },
    {
      title: '操作',
      render: (item) => {
        return (
          <div>
            <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => confirmMethod(item)} />
            <Popover content={<div style={{ textAlign: "center" }}> <Switch checked={item.pagepermisson} onClick={()=>swithMethod(item)} /> </div>} title="页面配置项" trigger={item.pagepermisson===undefined?'':'click'}>
              <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.pagepermisson===undefined}/>
            </Popover>
          </div>
        )
      }
    },
  ];
  useEffect(() => {
    const httpRequest=async ()=>{
      //获取权限列表信息
      const res=await getRights()
      const list = res.data.data;
      list.forEach(item => {
        if (item.children.length === 0) {
          item.children = "";
        }
      })
      setDataSource(list)
    }
    httpRequest()
  }, [])
  const confirmMethod = (item) => {
    Modal.confirm({
      title: '你确定要删除？',
      icon: <ExclamationCircleOutlined />,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        deleteMethod(item)
      }
    });
  }
  const deleteMethod = (item) => {
    console.log(item)
    if (item.grade === 1) {
      setDataSource(dataSource.filter(data => data.id !== item.id))
      //删除一级权限信息
      deleteRights({
        id:item.id
      })
    } else {
      let list = dataSource.filter(data => data.id === item.rightId)
      list[0].children = list[0].children.filter(data => data.id !== item.id)
      setDataSource([...dataSource])
      //删除子权限信息
      deleteChildren({
        id:item.id
      })
    }
  }
  const swithMethod=(item)=>{
    item.pagepermisson=item.pagepermisson===1?0:1;
    setDataSource([...dataSource]);
    if(item.grade===1){
      //修改一级权限信息
      updateRights({
        id:item.id,
        pagepermisson:item.pagepermisson
      })
    }else{
      //修改子权限信息
      updateChildren({
        id:item.id,
        pagepermisson:item.pagepermisson
      })
    }
  }
  return (
    <div>
      <Table dataSource={dataSource} columns={columns} pagination={{
        pageSize: 5,
        pageSizeOptions:[]
      }} />
    </div>
  )
}
